﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Management;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace HCLSMod
{
    /// <summary>
    /// 基础函数，包括对象、结构体序列化功能
    /// </summary>
    public class BaseLib
    {
        #region 对象序列化
        /// <summary>
        /// 序列化对象，操作对象必须标记为[Serializable]
        /// </summary>
        /// <param name="pObj">需要被序列化的对象</param>
        /// <returns></returns>
        public static byte[] SerializeObject(object pObj)
        {
            if (pObj == null)
                return null;
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, pObj);
            memoryStream.Position = 0;
            byte[] read = new byte[memoryStream.Length];
            memoryStream.Read(read, 0, read.Length);
            memoryStream.Close();
            return read;
        }
        /// <summary>
        /// 还原被序列化的对象
        /// </summary>
        /// <param name="pBytes">被序列化的数据</param>
        /// <returns></returns>
        public static object DeserializeObject(byte[] pBytes)
        {
            object newOjb = null;
            if (pBytes == null)
                return newOjb;
            MemoryStream memoryStream = new MemoryStream(pBytes);
            memoryStream.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            newOjb = formatter.Deserialize(memoryStream);
            memoryStream.Close();
            return newOjb;
        }
        #endregion

        #region 结构体与字节数组互转
        //结构体转字节数组     
        public static byte[] StructToBytes(object structObj)
        {

            int size = Marshal.SizeOf(structObj);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structObj, buffer, false);
                byte[] bytes = new byte[size];
                Marshal.Copy(buffer, bytes, 0, size);
                return bytes;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        //字节数组转结构体     
        public static object BytesToStruct(byte[] bytes, Type strcutType)
        {
            int size = Marshal.SizeOf(strcutType);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(bytes, 0, buffer, size);
                return Marshal.PtrToStructure(buffer, strcutType);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        #endregion

        #region 基础函数
        /// <summary>
        /// 检查电子邮件地址是否符合要求
        /// </summary>
        /// <param name="fEmail"></param>
        /// <returns></returns>
        public static bool checkEmailFormat(string fEmail)
        {
            return Regex.IsMatch(fEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)" + @"|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
        /// <summary>
        /// 获得版权代码X
        /// </summary>
        /// <param name="fstrACode"></param>
        /// <returns></returns>
        public static string getAuthorCode(string fstrACode)
        {
            return (fstrACode + "LPBStudio" + fstrACode + "Timeew Roman").ToUpper();
        }
        /// <summary>
        /// 从GUID生产16位长度的短ID
        /// </summary>
        /// <param name="fNewGUID"></param>
        /// <returns></returns>
        public static string GenerateStringGUDID(Guid fNewGUID)
        {
            long i = 1;
            foreach (byte b in fNewGUID.ToByteArray())
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        //如果你想生成一个数字序列而不是字符串，你将会获得一个19位长的序列。下面的方法会把GUID转换为Int64的数字序列。
        public static long GenerateIntID(Guid fNewGUID)
        {
            byte[] buffer = fNewGUID.ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

        #endregion

        #region 格式转换
        /// <summary>
        /// 将整数转换为Hex字符串
        /// </summary>
        /// <param name="Value">等待转换的整数</param>
        /// <param name="StrLen">输出最小长度，默认0为不限长度</param>
        /// <returns></returns>
        public static string IntToHex(int Value,int StrLen=0)
        {
            string sResult = Convert.ToString(Value, 16);
            if (StrLen > 0)
                while (sResult.Length < StrLen)
                    sResult = "0" + sResult;
            return "0x" + sResult;
        }

        #endregion

    }

    #region (*运行中数据记录器 2017-09-03*)
    /// <summary>
    /// 运行中数据记录基础类型
    /// </summary>
    public class ZLRunRecordsBase
    {    
        /// <summary>
        /// 记录时间
        /// </summary>
        public DateTime DataTime { get; set; }
        /// <summary>
        /// 运行数据
        /// </summary>
        protected List<object> fDatas = new List<object>();
        /// <summary>
        /// 返回的数据组
        /// </summary>
        public object[] Datas
        {
            get { return fDatas.ToArray(); }
            set { fDatas = new List<object>(); }
        }

        public ZLRunRecordsBase()
        {
            // 创建时间
            DataTime = DateTime.Now;
        }

        public ZLRunRecordsBase(object[] fNewDatas) : this()
        {
            Datas = fNewDatas;
        }

        public virtual object GetRecord(int fIdx = 0)
        {
            object fResult = null;
            if ((fDatas.Count > 0) && (fDatas.Count > fIdx) && (fIdx >= 0))
            {
                fResult = fDatas[fIdx];
                fDatas.RemoveAt(fIdx);
            }
            return fResult;
        }
    }
    /// <summary>
    /// 字节数据的记录对象
    /// 父类型：ZLRunRecordsBase
    /// </summary>
    public class ZLByteDataRecord : ZLRunRecordsBase
    {
        /// <summary>
        /// 记录的数据
        /// </summary>
        public byte[] Datas_byte
        {
            get
            {
                List<byte> fBuf = new List<byte>();
                if (fDatas.Count > 0)
                    for (int i = 0; i < fDatas.Count; i++)
                        fBuf.Add((byte)fDatas[i]);
                return fBuf.ToArray();
            }
            set
            {
                fDatas.Clear();
                if (value.Length > 0)
                    for (int i = 0; i < value.Length; i++)
                        fDatas.Add(value[i]);
            }
        }


        public string RecRemark { get; set; }

        public ZLByteDataRecord() : base()
        {
            RecRemark = "";
        }

        public ZLByteDataRecord(byte[] fNewDatas) : this()
        {
            Datas_byte = fNewDatas;
        }

        public ZLByteDataRecord(byte[] fNewDatas,string sRecRemark) : this(fNewDatas)
        {
            RecRemark = sRecRemark;
        }
        private string fGetStrByBytes(byte[] fData)
        {
            string fStr = "";
            if ((fData != null) && (fData.Length > 0))
                foreach (byte fValue in fData)
                    fStr += string.Format("{0:X2} ", fValue);
            return fStr.Trim();
        }

        public string ToString(string fInfo)
        {
            string sInfo = fInfo;
            if (!string.IsNullOrEmpty(RecRemark))
                sInfo = "("+RecRemark + ")" + fInfo;
            return string.Format("[{0}]{1}({2}):{3}",
                DataTime.ToString("HH:mm:ss  fff"),
                sInfo,
                fDatas.Count.ToString(),          
                fGetStrByBytes(Datas_byte));            
        }


        public override string ToString()
        {
            return ToString(RecRemark);
        }

    }
    /// <summary>
    /// 系统错误记录管理模块
    /// </summary>
    public class ZLErrorRecord : ZLRunRecordsBase
    {
        protected Mutex thdMutex = new Mutex(false, Guid.NewGuid().ToString() + "ZLRunRecordsBase" + DateTime.Now.ToString());

        protected List<ZLByteDataRecord> tRxRecorder = new List<ZLByteDataRecord>();

        public int RxRecCount { get { return tRxRecorder.Count; } }

        public ZLByteDataRecord RxRecord
        {
            get
            {
                thdMutex.WaitOne();
                try
                {
                    ZLByteDataRecord tRecTmp = tRxRecorder[0];
                    tRxRecorder.RemoveAt(0);
                    return tRecTmp;
                }
                finally
                {
                    thdMutex.ReleaseMutex();
                }
            }
        }

        protected void SetRxRecord(ZLByteDataRecord tRecTmp)
        {
            thdMutex.WaitOne();
            try
            {
                tRxRecorder.Add(tRecTmp);
                if (tRxRecorder.Count > 1000)
                    tRxRecorder.RemoveAt(0);
            }
            finally
            {
                thdMutex.ReleaseMutex();
            }
        }

        protected List<ZLByteDataRecord> tTxRecorder = new List<ZLByteDataRecord>();

        public int TxRecCount { get { return tTxRecorder.Count; } }
        public ZLByteDataRecord TxRecord
        {
            get
            {
                thdMutex.WaitOne();
                try
                {
                    ZLByteDataRecord tRecTmp = tTxRecorder[0];
                    tTxRecorder.RemoveAt(0);
                    return tRecTmp;
                }
                finally
                {
                    thdMutex.ReleaseMutex();
                }
            }
        }

        protected void SetTxRecord(ZLByteDataRecord tRecTmp)
        {
            thdMutex.WaitOne();
            try
            {
                tTxRecorder.Add(tRecTmp);
                if (tTxRecorder.Count > 1000)
                    tTxRecorder.RemoveAt(0);
            }
            finally
            {
                thdMutex.ReleaseMutex();
            }
        }
        /// <summary>
        /// 所有系统错误事件，读取后不删除错误记录
        /// </summary>
        public Exception[] ErrorList
        {
            get
            {
                List<Exception> fBuf = new List<Exception>();
                if (fDatas.Count > 0)
                    for (int i = 0; i < fDatas.Count; i++)
                        fBuf.Add((Exception)fDatas[i]);
                return fBuf.ToArray();
            }
        }

        public ZLErrorRecord() : base()
        {

        }
        /// <summary>
        /// 提取指定索引的错误，默认提取第一个错误
        /// </summary>
        /// <param name="fIdx"></param>
        /// <returns>成功提取这返回错误，否则返回Null</returns>
        public Exception GetErrorEvent(int fIdx = 0)
        {
            Exception fResult = null;
            if ((fDatas.Count > 0) && (fDatas.Count > fIdx) && (fIdx >= 0))
            {
                fResult = (Exception)fDatas[fIdx];
                fDatas.RemoveAt(fIdx);
            }
            return fResult;
        }
        /// <summary>
        /// 将错误事件放入列表中
        /// </summary>
        /// <param name="fErrorEvent"></param>
        /// <returns>返回错误事件总数量</returns>
        public int PutErrorEvent(Exception fErrorEvent)
        {
            if (fErrorEvent != null)
                fDatas.Add(fErrorEvent);
            return fDatas.Count;
        }
        /// <summary>
        /// 清除所有错误事件
        /// </summary>
        public void ClearAllError()
        {
            fDatas.Clear();
        }
        /// <summary>
        /// 系统错误事件总数量
        /// </summary>
        /// <returns></returns>
        public int ErrorCount()
        {
            return fDatas.Count;
        }

    }
    #endregion

    /// <summary>
    /// 生成随机验证码
    /// </summary>
    public class PICCheckCode
    {
        /// <summary>
        /// 获得新的验证码
        /// </summary>
        /// <param name="fstrKey">验证码字符串</param>
        /// <returns></returns>
        public static MemoryStream GetNewCheckCodePic(ref string fstrKey)
        {
            Bitmap bmp = new Bitmap(100, 40);

            string chkCode = string.Empty;
            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y',
                                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k',  'm', 'n', 'p', 'r', 's', 't', 'w', 'x', 'y'};
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 10; i++)
            {
                int x1 = rnd.Next(100);
                int y1 = rnd.Next(40);
                int x2 = rnd.Next(100);
                int y2 = rnd.Next(40);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, 24);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 6, (float)1);
            }
            //画噪点 
            for (int i = 0; i < 100; i++)
            {
                int x = rnd.Next(bmp.Width);
                int y = rnd.Next(bmp.Height);
                Color clr = color[rnd.Next(color.Length)];
                bmp.SetPixel(x, y, clr);
            }
            // 边框
            g.DrawRectangle(new Pen(Color.Gray), 0, 0, bmp.Width - 1, bmp.Height - 1);
            //将验证码图片写入内存流，并将其以 "image/Png" 格式输出 
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            }
            finally
            {
                //显式释放资源 
                //bmp.Dispose();
                //g.Dispose();
            }
            fstrKey = chkCode;
            return ms;
        }
    }

    /// <summary>
    /// INI文件管理
    /// </summary>
    public class IniFile
    {
        /// <summary>
        /// 用输入的文件创建INI配置文件对象，如果输入文件名为空，则使用默认文件名称
        /// </summary>
        /// <param name="fDestFileName"></param>
        /// <returns></returns>
        public static string NewIniFileName(string fDestFileName="")
        {
            string newFile = "";
            if ((!string.IsNullOrEmpty(fDestFileName))&& File.Exists(fDestFileName))
                newFile = fDestFileName;
            else
                newFile = Application.ExecutablePath;
            newFile = newFile.Substring(0, newFile.Length - 4) + ".ini";
            return newFile;
        }

        #region WinAPI
        /// <summary>
        /// 将字符串写入注册表
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        /// <summary>
        /// 从注册表读取字符串
        /// </summary>
        /// <param name="lpAppName"></param>
        /// <param name="lpKeyName"></param>
        /// <param name="lpDefault"></param>
        /// <param name="lpReturnedString"></param>
        /// <param name="nSize"></param>
        /// <param name="lpFileName"></param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

        [DllImport("kernel32", EntryPoint = "GetPrivateProfileSectionW", CharSet = CharSet.Unicode)]
        public static extern int GetPrivateProfileSection(
            string lpApplicationName,
            byte[] lpReturnedString,
            int nSize,
            string lpFileName);
        #endregion

        #region API封装
        /// <summary>
        /// 根据section，key取值
        /// </summary>
        /// <param name="section">分类名称</param>
        /// <param name="keys">属性名称</param>
        /// <param name="lpDefault">属性默认值，当属性不存在，则返回该默认值</param>
        /// <param name="filePath">ini文件路径</param>
        /// <returns>string</returns>
        public static string ReadIniKeys(string section, string key, string lpDefault, string filePath)
        {
            StringBuilder stemp = new StringBuilder(2048);
            try
            {
                GetPrivateProfileString(section, key, lpDefault, stemp, 2048, filePath);
            }
            catch
            {
                throw new Exception("无法打开INI文件信息！");
            }
            return stemp.ToString();
        }

        /// <summary>
        /// 保存ini
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="filePath">ini文件路径</param>
        public static void WriteIniKeys(string section, string key, string value, string filePath)
        {
            WritePrivateProfileString(section, key, value, filePath);
        }


        #endregion

        #region 初始化
                
        public IniFile(string sFileName)
        {
            IniFileName = sFileName;
        }

        public string IniFileName { get; set; }
        #endregion
        
        #region 外部功能函数
        /// <summary>
        /// 读取注册表
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="lpDefault"></param>
        /// <returns></returns>
        public string ReadIniKeys(string section, string key, string lpDefault)
        {
            string stemp = "";
            stemp = lpDefault;
            if (IniFileName != "")
                stemp = ReadIniKeys(section, key, lpDefault, IniFileName);
            return stemp;
        }
        /// <summary>
        /// 写入注册表
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void WriteIniKeys(string section, string key, string value)
        {
            if (IniFileName != "")
                WriteIniKeys(section, key, value, IniFileName);
        }
        #endregion
    }

    /// <summary>
    /// 注册表控制
    /// </summary>
    public class LicRegInfo
    {
        #region 程序初始化
        public RegistryKey key = Registry.LocalMachine;
        private RegistryKey FEncRight = null;
        private RegistryKey fSoftAuthor = null;
        /// <summary>
        /// 程序ID，直接控制其他关键信息的保存，
        /// </summary>
        public int AppID { get; set; }
        public LicRegInfo()
            : this(0)
        {
        }

        public LicRegInfo(int fAppID)
        {
            AppID = fAppID;
            fSoftAuthor = key.CreateSubKey("software\\LPBStudio");

            FEncRight = key.CreateSubKey("SOFTWARE\\Microsoft\\ADs\\Providers\\WinNT\\Extensions");

        }
        #endregion

        #region 用户资料
        /// <summary>
        /// 用户名称
        /// </summary>
        public string UserName
        {
            get
            {
                return (string)fSoftAuthor.GetValue("UserName", "");
            }
            set
            {
                fSoftAuthor.SetValue("UserName", value, RegistryValueKind.String);
            }
        }
        /// <summary>
        /// 用户联系方式
        /// </summary>
        public string UserPhone
        {
            get
            {
                return (string)fSoftAuthor.GetValue("UserPhone", "");
            }
            set
            {
                fSoftAuthor.SetValue("UserPhone", value, RegistryValueKind.String);
            }
        }
        /// <summary>
        /// 用户地址
        /// </summary>
        public string UserAddress
        {
            get
            {
                return (string)fSoftAuthor.GetValue("UserAddress", "");
            }
            set
            {
                fSoftAuthor.SetValue("UserAddress", value, RegistryValueKind.String);
            }
        }
        #endregion

        #region 许可信息
        /// <summary>
        /// 许可字符串
        /// </summary>
        /// <param name="AppID"></param>
        /// <returns></returns>
        public string getLicInfo(int AppID)
        {
            return (string)FEncRight.GetValue("KeyInfo_" + AppID.ToString(), "");
        }
        /// <summary>
        /// 将许可字符串保存到系统注册表中
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="sLicStr"></param>
        /// <returns></returns>
        public int setLicInfo(int AppID, string sLicStr)
        {
            FEncRight.SetValue("KeyInfo_" + AppID.ToString(), sLicStr, RegistryValueKind.String);
            return AppID;
        }

        /// <summary>
        /// 许可起始日期
        /// </summary>
        public DateTime LicBaseDate
        {
            get
            {
                DateTime fDTemp = new DateTime(2000, 1, 1);
                if (AppID > 0)
                    DateTime.TryParse((string)FEncRight.GetValue("LicBaseDate_" + AppID.ToString(), fDTemp.ToString("yyyy/MM/dd")), out fDTemp);
                else
                    DateTime.TryParse((string)FEncRight.GetValue("LicBaseDate", fDTemp.ToString("yyyy/MM/dd")), out fDTemp);
                return fDTemp;
            }
            set
            {
                if (AppID > 0)
                    FEncRight.SetValue("LicBaseDate_" + AppID.ToString(), value.ToString("yyyy/MM/dd"), RegistryValueKind.String);
                else
                    FEncRight.SetValue("LicBaseDate", value.ToString("yyyy/MM/dd"), RegistryValueKind.String);
            }
        }
        /// <summary>
        /// 许可能够使用的天数
        /// </summary> 
        public int LicDayCount
        {
            get
            {
                if (AppID > 0)
                    return int.Parse((string)FEncRight.GetValue("LicDays_" + AppID.ToString(), "1"));
                else
                    return int.Parse((string)FEncRight.GetValue("LicDays", "1"));
            }
            set
            {
                if (AppID > 0)
                    FEncRight.SetValue("LicDays_" + AppID.ToString(), value.ToString(), RegistryValueKind.String);
                else
                    FEncRight.SetValue("LicDays", value.ToString(), RegistryValueKind.String);
            }
        }
        /// <summary>
        /// 许可已经使用的天数
        /// </summary>
        public int LicDayPass
        {
            get
            {
                if (AppID > 0)
                    return int.Parse((string)FEncRight.GetValue("LicDayPass_" + AppID.ToString(), "1"));
                else
                    return int.Parse((string)FEncRight.GetValue("LicDayPass", "1"));
            }
            set
            {
                if (AppID > 0)
                    FEncRight.SetValue("LicDayPass_" + AppID.ToString(), value.ToString(), RegistryValueKind.String);
                else
                    FEncRight.SetValue("LicDayPass", value.ToString(), RegistryValueKind.String);
            }
        }
        /// <summary>
        /// 许可使用的次数
        /// </summary>
        public int LicCanUseCount
        {
            get
            {
                if (AppID > 0)
                    return int.Parse((string)FEncRight.GetValue("LicCanUseCount_" + AppID.ToString(), "1"));
                else
                    return int.Parse((string)FEncRight.GetValue("LicCanUseCount", "1"));
            }
            set
            {
                if (AppID > 0)
                    FEncRight.SetValue("LicCanUseCount_" + AppID.ToString(), value.ToString(), RegistryValueKind.String);
                else
                    FEncRight.SetValue("LicCanUseCount", value.ToString(), RegistryValueKind.String);
            }
        }
        /// <summary>
        /// 许可已经使用的次数
        /// </summary>
        public int LicUsedCount
        {
            get
            {
                if (AppID > 0)
                    return int.Parse((string)FEncRight.GetValue("LicUsedCount_" + AppID.ToString(), "1"));
                else
                    return int.Parse((string)FEncRight.GetValue("LicUsedCount", "1"));
            }
            set
            {
                if (AppID > 0)
                    FEncRight.SetValue("LicUsedCount_" + AppID.ToString(), value.ToString(), RegistryValueKind.String);
                else
                    FEncRight.SetValue("LicUsedCount", value.ToString(), RegistryValueKind.String);
            }
        }
        #endregion

        #region 外部调用函数
        /// <summary>
        /// 写入注册表
        /// </summary>
        /// <param name="regKey">键名</param>
        /// <param name="regValue">键值</param>
        /// <param name="isAuthorInfo">是版权信息</param>
        /// <returns></returns>
        public bool writeRegInfo(string regKey, string regValue, bool isAuthorInfo = true)
        {
            if (isAuthorInfo)
                fSoftAuthor.SetValue(regKey, regValue, RegistryValueKind.String);
            else
                FEncRight.SetValue(regKey + "_" + AppID.ToString(), regValue, RegistryValueKind.String);
            return true;
        }
        /// <summary>
        /// 读取注册表
        /// </summary>
        /// <param name="regKey"></param>
        /// <param name="regDefValue"></param>
        /// <param name="isAuthorInfo"></param>
        /// <returns></returns>
        public string readRegInfo(string regKey, string regDefValue, bool isAuthorInfo = true)
        {
            if (isAuthorInfo)
                return (string)fSoftAuthor.GetValue(regKey, regDefValue);
            else
                return (string)FEncRight.GetValue(regKey + "_" + AppID.ToString(), regDefValue);
        }
        #endregion
    }
    /// <summary>
    /// 获得硬件信息
    /// </summary>
    public class SysHardInfo
    {
        public static string GetHDKey()
        {
            return TSecurity.GetMD5HashFromString(GetHDInfo());
        }

        public static string GetHDKey(Guid fAppID)
        {
            return TSecurity.GetMD5HashFromString(GetHDInfo() + ":" + fAppID.ToString());
        }
        public static string GetHDKeyMac()
        {
            return TSecurity.GetMD5HashFromString(GetHDInfoMAC());
        }
        public static string GetHDKeyMac(Guid fAppID)
        {
            return TSecurity.GetMD5HashFromString(GetHDInfoMAC() + ":" + fAppID.ToString());
        }
        /// <summary>
        /// 获得系统硬件信息，不包括网卡MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetHDInfo()
        {
            return GetCpuId() + ":" + GetHdId() + ":" + GetMbId();
        }
        /// <summary>
        /// 获得系统硬件信息，包括网卡MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetHDInfoMAC()
        {
            return GetCpuId() + ":" + GetHdId() + ":" + GetMbId() + ":" + GetMacID();
        }
        /// <summary>
        /// 获取CPU序列号
        /// 改20151031：增加了CPU数量、内存大小
        /// </summary>
        /// <returns></returns>
        private static String GetCpuId()
        {
            var myCpu = new ManagementClass("win32_Processor").GetInstances();
            var serial = "";
            foreach (ManagementObject cpu in myCpu)
            {
                var val = cpu.Properties["Processorid"].Value;
                serial += val == null ? "" : val.ToString()+"\r\n";
            }
            
            ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
                foreach (var fObj in mo.Properties)
                {
                    if (fObj != null)
                    {// CPU内核数量、物理CPU数量、主板厂家、主板型号、系统类型、内存大小
                        if ((fObj.Name == "NumberOfLogicalProcessors") || (fObj.Name == "NumberOfProcessors") ||
                            (fObj.Name == "Manufacturer") || (fObj.Name == "Model") ||
                            (fObj.Name == "SystemType") || (fObj.Name == "TotalPhysicalMemory"))
                            serial += fObj.Name + ":" + (fObj.Value != null ? fObj.Value.ToString() : "") + ";\r\n";
                    }
                }
            return serial;
        }

        /// <summary>
        /// 获取主板信息
        /// </summary>
        /// <returns></returns>
        private static String GetMbId()
        {
            try
            {
                ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_baseboard");
                string serNumber = string.Empty;
                string manufacturer = string.Empty;
                string product = string.Empty;

                foreach (ManagementObject m in mos.Get())
                {
                    serNumber = m["SerialNumber"].ToString();//序列号
                    manufacturer = m["Manufacturer"].ToString();//制造商
                    product = m["Product"].ToString();//型号
                }
                return serNumber + ":" + manufacturer + ":" + product + "\r\n"; 
            }
            catch
            {
                return "likePnayt";
            }
        }
        /// <summary>
        /// 获取硬盘序列号
        /// 改20151031：程序仅读取第一硬盘的序列号，
        /// 该程序会读取系统中所有接驳的硬盘内设备，包括：硬盘、U盘、光盘等，因此当用户插拔U盘时，会造成序列号不正确
        /// </summary>
        /// <returns></returns>
        private static String GetHdId()
        {
            var lpm = new ManagementClass("Win32_PhysicalMedia").GetInstances();
            string serial = "NoHarddisk";
            foreach (ManagementObject hd in lpm)
            {
                if ((hd.Properties["Tag"].Value != null) && (hd.Properties["Tag"].Value.ToString().EndsWith("PHYSICALDRIVE0")))
                {
                    var val = hd.Properties["SerialNumber"].Value;
                    serial = "PHYSICALDRIVE0" + (val != null ? val.ToString().Trim() : "") + "\r\n"; ;
                }
            }
            return serial;
        }
        /// <summary>
        /// 获得网卡信息
        /// </summary>
        /// <returns></returns>
        private static string GetMacID()
        {
            try
            {
                string MoAddress = string.Empty;
                ManagementClass networkAdapter = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection adapterC = networkAdapter.GetInstances();
                foreach (ManagementObject m in adapterC)
                {
                    if ((bool)m["IPEnabled"] == true)
                    {
                        MoAddress += m["MacAddress"].ToString().Trim()+";\r\n";
                        m.Dispose();
                    }
                }
                return MoAddress;
            }
            catch
            {
                return "";
            }
        }
    }
}
